<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box page-uc-return">
    <!-- 导航 -->
    <div class="uc-nav">
      <div class="nav-box">
        <div
          :class="['nav-item', sts === 0 ? 'active' : '']"
          @click="changeTab(0)"
        >
          <span class="text">{{ $t('all') }}</span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', sts === 1 ? 'active' : '']"
          @click="changeTab(1)"
        >
          <span class="text">{{ $t('applyReturn.refundsOnly') }}</span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', sts === 2 ? 'active' : '']"
          @click="changeTab(2)"
        >
          <span class="text">{{ $t('applyReturn.returnsAndRefunds') }}</span>
          <i class="line" />
        </div>
      </div>
    </div>
    <!-- /导航 -->
    <!-- 订单列表 -->
    <div class="order-list">
      <div class="order-table">
        <table
          style="border-spacing: 0"
          class="box"
        >
          <tbody>
            <tr class="box-tit">
              <th>{{ $t('applyReturn.productInformation') }}</th>
              <th style="width: 127px">
                {{ $t('applyReturn.returnType') }}
              </th>
              <th style="width: 127px">
                {{ $t('applyReturn.refundAmount') }}
              </th>
              <th style="width: 147px">
                {{ $t('applyReturn.applicationTime') }}
              </th>
              <th style="width: 127px">
                {{ $t('applyReturn.processingStatus') }}
              </th>
              <th style="width: 127px">
                {{ $t('operation') }}
              </th>
            </tr>
          </tbody>
          <tbody
            v-for="item in page.records"
            :key="item.refundId"
          >
            <tr class="box-space">
              <td colspan="6" />
            </tr>
            <tr class="box-hd">
              <td colspan="6">
                <div class="order-number">
                  {{ $t('applyReturn.orderNumber') }}：
                  <span class="num">{{ item.orderNumber }}</span>
                </div>
                <div class="return-number">
                  {{ $t('applyReturn.refundNumber') }}：
                  <span class="num">{{ item.refundSn }}</span>
                </div>
                <router-link
                  :to="{
                    path: '/shop-index',
                    query: { sid: item.shopId }
                  }"
                  class="shop"
                >
                  <span class="shop-icon" />
                  {{ item.shopName }}
                </router-link>
                <a
                  href="JavaScript:void(0);"
                  class="btn-im"
                  style="float: left;"
                  @click="toChat(item.shopId, item.orderNumber)"
                />
              </td>
            </tr>
            <tr
              v-for="(refund,index) in item.orderItems"
              :key="index"
              class="box-tr"
            >
              <td>
                <div class="goods-info">
                  <div class="img">
                    <img
                      v-if="refund.pic"
                      :src="checkFileUrl(refund.pic)"
                      alt
                      @error="handlePicError"
                    >
                    <img
                      v-else
                      src="@/assets/img/def.png"
                      alt
                    >
                  </div>
                  <div class="name-sku">
                    <span
                      class="name"
                      @click.stop="toProdDetail(item.orderType,refund.prodId)"
                    >{{ refund.prodName }}</span>
                    <span class="sku">
                      <span
                        v-if="refund.skuName"
                        style="max-width:85%"
                      >{{ refund.skuName }}</span>
                      <span>x {{ item.refundType === 1 ? refund.prodCount : item.goodsNum }}</span>
                    </span>
                  </div>
                </div>
                <div
                  v-if="refund.giveawayList"
                  class="gift-group"
                >
                  <div
                    v-for="(orderGift, giftIndex) in refund.giveawayList"
                    :key="giftIndex"
                    class="gift-item"
                  >
                    <div class="giveaway-item-name">
                      【{{ $t('prodDetail.gift') }}】 {{ orderGift.prodName }}
                    </div>
                    <div class="giveaway-item-sku-count">
                      {{ orderGift.skuName || '' }} x{{ orderGift.prodCount }}
                    </div>
                  </div>
                </div>
              </td>
              <td
                v-if="index === 0"
                :rowspan="item.orderItems.length"
              >
                <span class="return-type">{{ ['',$t('applyReturn.refundsOnly'),$t('applyReturn.returnsAndRefunds')][item.applyType] }}</span>
              </td>
              <td
                v-if="index === 0"
                :rowspan="item.orderItems.length"
              >
                <span v-if="item.refundAmount">￥{{ (item.refundAmount).toFixed(2) }}</span>
                <span v-if="item.refundAmount && item.refundScore">+</span>
                <span v-if="item.refundScore">{{ item.refundScore }}{{ $t('applyReturn.points') }}</span>
              </td>
              <td
                v-if="index === 0"
                :rowspan="item.orderItems.length"
              >
                <div class="apply-time">
                  {{ item.applyTime }}
                </div>
              </td>
              <td
                v-if="index === 0"
                :rowspan="item.orderItems.length"
              >
                <div
                  v-if="item.platformInterventionStatus && item.platformInterventionStatus !== -1"
                  class="status"
                >
                  <div
                    class="text no-finish"
                  >
                    {{ ['','待处理','进行中','已关闭','','已完成'][item.platformInterventionStatus] }}
                  </div>
                  <div class="text no-finish">
                    {{
                      [
                        '',
                        '平台介入中',
                        '平台介入中',
                        '退款关闭',
                        '',
                        '退款成功'
                      ][item.platformInterventionStatus]
                    }}
                  </div>
                </div>
                <div
                  v-else
                  class="status"
                >
                  <div
                    class="text no-finish"
                  >
                    {{ ['',$t('applyReturn.buyerApplication'),$t('applyReturn.sellerAcceptance'),$t('applyReturn.buyerShipping'),$t('applyReturn.sellerReceipt'),$t('applyReturn.successfulRefund'),$t('applyReturn.buyerWithdrawsApplication'),$t('applyReturn.merchantRefusal'),$t('applyReturn.refundClose')][item.returnMoneySts] }}
                  </div>
                  <div
                    v-if="item.returnMoneySts === -1"
                    class="text no-finish"
                  >
                    {{ $t('applyReturn.refundClose') }}
                  </div>
                </div>
              </td>
              <td
                v-if="index === 0"
                :rowspan="item.orderItems.length"
              >
                <div class="action">
                  <router-link
                    :to="{
                      path:'/return-detail',
                      query: {
                        refundSn: item.refundSn
                      }
                    }"
                    class="action-btn default"
                  >
                    {{ $t('applyReturn.viewDetails') }}
                  </router-link>
                  <router-link
                    v-if="item.platformInterventionStatus === 1 && item.isUserHandle"
                    :to="{
                      path: '/user-center/return-proof',
                      query: { proofType: 2,refundId: item.refundId}
                    }"
                    class="action-btn active m-t"
                  >
                    补充凭证
                  </router-link>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- 空列表提示 -->
        <empty-all-tips
          v-if="isEmpty"
          :text="$t('applyReturn.noRelatedRecords')"
          :back="$t('backToHome')"
        />
        <!-- /空列表提示 -->
      </div>
      <pagination
        v-model="page.current"
        :pages="page.pages"
        @change-page="getMyRefundOrder"
      />
    </div>
    <!-- /订单列表 -->
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import defPng from '@/assets/img/def.png'
import { ElMessage } from 'element-plus'
import { checkFileUrl } from '@/utils/index.js'
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const page = ref({
  records: [],
  total: 0, // 总条
  pages: 0, // 总页数
  current: route.query.current, // 当前页数
  size: 5 // 每页显示多少条
})
onMounted(() => {
  page.value.current = 1
  // 设置网页标题
  document.title = $t('applyReturn.refunds')
  getMyRefundOrder() // 我的退款订单列表
})
onUnmounted(() => {
  clearTimeout(timer)
})

/**
 * 加载默认图片
 */
const handlePicError = (e) => {
  e.target.src = defPng
}

/**
 * 跳转商品详情
 */
const toProdDetail = (orderType, prodId) => {
  let newPage
  const toDetail = () => {
    let userId = null
    if (Cookie.get('bbcToken')) {
      userId = userStore.userId
    }
    http.get('/prod/prodInfo', {
      params: {
        prodId,
        userId
      }
    }).then(() => {
      window.open(newPage.href, '_blank', 'noopener,noreferrer')
    })
  }
  switch (orderType) {
    case 0:
      newPage = router.resolve({ path: '/detail', query: { prodId } })
      toDetail()
      break
    case 1:
      newPage = router.resolve({ path: '/detail', query: { prodId } })
      toDetail()
      break
    case 2:
      //  秒杀商品活动是否结束
      http.get('/p/seckill/prod', {
        params: {
          prodId
        }
      }).then(({ data }) => {
        if (data) {
          newPage = router.resolve({ path: '/detail', query: { prodId } })
          window.open(newPage.href, '_blank', 'noopener,noreferrer')
        } else {
          ElMessage.warning($t('spike.currentSecondsAreOver'))
        }
      })
      break
    default:
      break
  }
}

/**
 * 跳转客服
 */
const toChat = (shopId, orderNumber) => {
  const shoppId = shopId || 1
  let routeUrl
  if (shopId == null) {
    routeUrl = router.resolve({
      path: '/chat',
      query: {
        shopId: shoppId,
        chatType: 1,
        orderNumber
      }
    })
  } else {
    routeUrl = router.resolve({
      path: '/chat',
      query: {
        shopId: shoppId,
        orderNumber
      }
    })
  }
  window.open(routeUrl.href, 'view_window')
}

const isEmpty = ref(false)
const sts = ref(0) // 申请类型: 0/null 全部 1仅退款 2退款退货
/**
 * 我的退款订单列表
 */
const getMyRefundOrder = (current) => {
  isEmpty.value = false
  clearTimeout(timer)
  http.get('/p/orderRefund/list', {
    params: {
      current: current || page.value.current,
      size: 5,
      applyType: sts.value
    }
  }).then(({ data }) => {
    page.value = data
    isEmpty.value = !page.value.records.length
    if (page.value.current !== undefined) {
      localStorage.setItem('bbcReturnCurrent', JSON.stringify(page.value.current))
    }
    intervenEndTimeCountdown()
  })
}

// 添加凭证时间结束倒计时
let timer = null
const intervenEndTimeCountdown = () => {
  let count = 0 // 计算申请平台介入的订单项数
  for (const refundItem of page.value.records) {
    const nowTime = new Date().getTime() // 当前时间
    if (refundItem.platformInterventionStatus === 1 && refundItem.interventionEndTime) {
      const endTime = new Date(refundItem.interventionEndTime).getTime() // 设置截止时间
      const leftTime = endTime - nowTime // 时间差
      if (leftTime >= 0) {
        count++
        refundItem.isUserHandle = true
      } else {
        refundItem.isUserHandle = false
      }
    }
  }
  // 当前列表存在申请平台介入的订单项时进行递归
  if (count) {
    // 递归每秒调用countTime方法，显示动态时间效果,
    timer = setTimeout(intervenEndTimeCountdown, 1000)
  }
}

/**
 * 改变tab
 */
const changeTab = (stsPar) => {
  page.value.current = 1
  sts.value = stsPar // 0全部 1仅退款 2退货退款
  getMyRefundOrder()
}

</script>

<style lang="scss" scoped>
@use "index";
</style>

<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
